import { prisma } from "@/lib/prisma"
import { getServerSession } from "next-auth"
import { NextResponse } from "next/server"
import { authOptions } from "@/lib/auth"

export async function GET() {
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.isAdmin) {
      return NextResponse.json({ error: "未授权访问" }, { status: 401 })
    }

    const libraries = await prisma.eventLibrary.findMany({
      include: {
        _count: {
          select: { events: true }
        }
      },
      orderBy: { createdAt: "desc" }
    })

    return NextResponse.json(
      libraries.map(lib => ({
        id: lib.id,
        name: lib.name,
        description: lib.description,
        eventCount: lib._count.events,
        createdAt: lib.createdAt
      }))
    )

  } catch (error) {
    return NextResponse.json(
      { error: "加载事件库失败" },
      { status: 500 }
    )
  }
}

export async function POST(req: Request) {
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.isAdmin) {
      return NextResponse.json({ error: "未授权访问" }, { status: 401 })
    }

    const { name, description } = await req.json()

    const library = await prisma.eventLibrary.create({
      data: {
        name,
        description
      }
    })

    return NextResponse.json(library)

  } catch (error) {
    return NextResponse.json(
      { error: "创建事件库失败" },
      { status: 500 }
    )
  }
} 